import { getUserRole } from '@/api/user'
import store from '..';

const permission = {
  state: {
    routes: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.routes = routes;
    },
  },
  actions: {
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        getUserRole().then(res => {
          let routes = []
          routes.push(...['/', '/login', '/forgetPassword', '/register', '/401', '/404', '/test/video'])
          if (store.getters.test) {
            commit('SET_ROUTES', res.data)
            routes.push(...toRoutes(res.data))
            routes.push(...['/personal', '/teaching/detail', '/data/analysis/record'])
          } else {
            routes.push(...['/test/user', '/test/recording', '/test/planeGame', '/test/management', '/test/report'])
          }
          resolve(routes);
        });
      });
    },
  },
};

function toRoutes(data) {
  let routes = [];
  for (let item of data) {
    if (item.routeConfigList.length === 0) {
      routes.push(item.path);
    } else {
      routes = routes.concat(toRoutes(item.routeConfigList));
    }
  }
  return routes;
}

export default permission;
